package sim.ring.tower;

import sim.ring.method.*;

import java.util.Random;
import java.util.Vector;

public class Tower {
	private int id=-1;
	private Vector<Bell> bells = new Vector<Bell>();
	private int numBells=0;
	private String name="";
	private String town="";
	private String key="";
	
	
	public Tower(int numBells) {
		this.numBells=numBells;
		for(int i=1;i<=numBells;i++) {
			Bell bell = new Bell(i,"bin/"+(i)+".wav");
			bell.setTower(this);
			bells.add(bell);
			//QueryBuilder.saveBell(bell);
		}
	}
	
	public Tower(String name, String town, int numBells, String key) {
		this.name=name;
		this.town=town;
		this.numBells=numBells;
		this.key=key;

		for(int i=1;i<=numBells;i++) {
			Bell bell = new Bell(i,"bin/"+(i)+".wav");
			bell.setTower(this);
			bells.add(bell);
			//QueryBuilder.saveBell(bell);
		}
	}
	
	public Tower(int id, String name, String town, int numBells, String key) {
		this.id=id;
		this.name=name;
		this.town=town;
		this.numBells=numBells;
		this.key=key;
		
		for(int bellnr=1;bellnr<=numBells;bellnr++) {
			Bell bell = BellQueryBuilder.loadBell(id, bellnr);
			bell.setTower(this);
			bells.add(bell);
		}
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id=id;
	}
	
	public int getNumBells() {
		return numBells;
	}
	
	public String getName() {
		return name;
	}
	
	public String getTown() {
		return town;
	}
	
	public String getKey() {
		return key;
	}
	
	public Vector<Bell> getBells() {
		return bells;
	}
	
	
	public void ringMethod(Method method, int speed) {
		Random randomGenerator = new Random();
		boolean handstroke=true;
		while(true) { //TODO: yeah
			int[] row=method.getRowToRing();
			for(int bell : row) { 
				System.out.print(bell);
				ringBell(bell);
				try {
					boolean negative = randomGenerator.nextBoolean();
					int randomNumber = randomGenerator.nextInt(1);
					if(negative)
						randomNumber=0-randomNumber;
					Thread.sleep(speed+randomNumber);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if(!handstroke) {
				handstroke=true;
				try {
					boolean negative = randomGenerator.nextBoolean();
					int randomNumber = randomGenerator.nextInt(1);
					if(negative)
						randomNumber=0-randomNumber;
					Thread.sleep(speed+randomNumber);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				handstroke=false;
			}
			System.out.println();
		}
	}
	
	public void ringBell(int bell) {
		bells.elementAt(bell-1).ring();
	}
}
